'use client'

import { useState } from 'react';

export default function AppointmentSystem() {
  // 状态管理
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    otherContact: '',
    remark: ''
  });
  const [reservedSlots, setReservedSlots] = useState<Record<string, string[]>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submissionSuccess, setSubmissionSuccess] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 生成时间槽（9:00-18:00，每30分钟一个槽）
  const generateTimeSlots = () => {
    const slots = [];
    for (let hour = 9; hour < 18; hour++) {
      for (let minute = 0; minute < 60; minute += 30) {
        const nextHour = minute === 30 ? hour + 1 : hour;
        const nextMinute = minute === 30 ? 0 : 30;
        
        slots.push({
          start: `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`,
          end: `${nextHour.toString().padStart(2, '0')}:${nextMinute.toString().padStart(2, '0')}`,
          id: `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}-${nextHour.toString().padStart(2, '0')}:${nextMinute.toString().padStart(2, '0')}`
        });
      }
    }
    return slots;
  };

  const timeSlots = generateTimeSlots();

  // 生成当前月份的日历数据
  const generateCalendarDays = () => {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const firstDay = new Date(year, month, 1).getDay();

    const days = [];
    // 填充上个月的日期（灰色显示）
    for (let i = 0; i < firstDay; i++) {
      const prevMonthDate = new Date(year, month, -firstDay + i + 1);
      days.push({
        date: prevMonthDate,
        isCurrentMonth: false,
        isToday: false,
        isSelected: false
      });
    }
    // 填充当前月份的日期
    for (let i = 1; i <= daysInMonth; i++) {
      const date = new Date(year, month, i);
      days.push({
        date: date,
        isCurrentMonth: true,
        isToday: date.toDateString() === today.toDateString(),
        isSelected: selectedDate && date.toDateString() === selectedDate.toDateString()
      });
    }
    return days;
  };

  const calendarDays = generateCalendarDays();

  // 处理日期选择
  const handleDateSelect = async (date: Date) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 只允许选择今天及以后的日期
    if (date >= today) {
      setSelectedDate(date);
      setSelectedTimeSlot(null);
      
      // 从API获取已预约的时间段
      const dateKey = date.toISOString().split('T')[0];
      try {
        const response = await fetch(`/api/appointments?date=${dateKey}`);
        if (response.ok) {
          const data = await response.json();
          setReservedSlots({ [dateKey]: data.reservedSlots });
        } else {
          console.error('获取已预约时间段失败');
          // 如果API调用失败，使用模拟数据
          const mockReservedSlots: Record<string, string[]> = {
            [dateKey]: []
          };
          setReservedSlots(mockReservedSlots);
        }
      } catch (error) {
        console.error('获取已预约时间段时发生错误:', error);
        // 如果发生错误，使用模拟数据
        const mockReservedSlots: Record<string, string[]> = {
          [dateKey]: []
        };
        setReservedSlots(mockReservedSlots);
      }
    }
  };

  // 处理时间段选择
  const handleTimeSlotSelect = (slotId: string) => {
    setSelectedTimeSlot(slotId);
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 清除对应字段的错误提示
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    
    if (!formData.name.trim()) {
      newErrors.name = '姓名不能为空';
    }
    
    if (!formData.phone.trim()) {
      newErrors.phone = '手机号码不能为空';
    } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      newErrors.phone = '请输入正确的手机号码';
    }
    
    if (!selectedDate) {
      newErrors.date = '请选择预约日期';
    }
    
    if (!selectedTimeSlot) {
      newErrors.time = '请选择预约时间段';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      // 构建提交数据
      const appointmentData = {
        ...formData,
        date: selectedDate?.toISOString().split('T')[0],
        timeSlot: selectedTimeSlot
      };
      
      // 发送到API
      const response = await fetch('/api/appointments', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(appointmentData)
      });
      
      if (response.ok) {
        const data = await response.json();
        console.log('预约成功:', data);
        
        // 显示成功提示
        setSubmissionSuccess(true);
        
        // 5秒后重置表单
        setTimeout(() => {
          resetForm();
        }, 5000);
      } else {
        const errorData = await response.json();
        console.error('提交失败:', errorData.error);
        // 显示错误信息
        alert(`提交失败: ${errorData.error}`);
      }
    } catch (error) {
      console.error('提交时发生错误:', error);
      alert('网络错误，请稍后重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      phone: '',
      otherContact: '',
      remark: ''
    });
    setSelectedDate(null);
    setSelectedTimeSlot(null);
    setSubmissionSuccess(false);
    setErrors({});
  };

  // 检查时间段是否已被预约
  const isSlotReserved = (slotId: string): boolean => {
    if (!selectedDate) return false;
    const dateKey = selectedDate.toISOString().split('T')[0];
    return reservedSlots[dateKey]?.includes(slotId) || false;
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <h1 className="text-3xl font-bold text-center text-gray-900 mb-12">
          咨询预约系统
        </h1>

        {submissionSuccess ? (
          <div className="bg-green-50 border border-green-200 rounded-lg p-8 text-center fade-in">
            <h2 className="text-2xl font-bold text-green-700 mb-4">预约成功！</h2>
            <p className="text-green-600 mb-6">
              感谢您的预约，我们将尽快与您联系确认详情。
            </p>
            <div className="bg-white p-4 rounded-lg shadow-sm inline-block">
              <p className="text-gray-800">
                <span className="font-medium">预约日期：</span>
                {selectedDate?.toLocaleDateString('zh-CN')}
              </p>
              <p className="text-gray-800">
                <span className="font-medium">预约时间：</span>
                {selectedTimeSlot}
              </p>
              <p className="text-gray-800">
                <span className="font-medium">预约人：</span>
                {formData.name}
              </p>
              <p className="text-gray-800">
                <span className="font-medium">联系电话：</span>
                {formData.phone}
              </p>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* 日历选择区域 */}
            <div className="lg:col-span-2 bg-white rounded-lg shadow-md p-6 fade-in">
              <h2 className="text-xl font-semibold text-gray-800 mb-6">
                选择预约日期和时间
              </h2>
              
              {/* 日历控件 */}
              <div className="mb-8">
                <div className="grid grid-cols-7 gap-2 mb-4">
                  {['日', '一', '二', '三', '四', '五', '六'].map(day => (
                    <div key={day} className="text-center font-medium text-gray-500">
                      {day}
                    </div>
                  ))}
                  
                  {calendarDays.map((day, index) => {
                    const dateKey = day.date.toISOString().split('T')[0];
                    const today = new Date().toISOString().split('T')[0];
                    const isPastDate = dateKey < today && day.isCurrentMonth;
                    
                    return (
                      <button
                        key={index}
                        className={`
                          h-12 rounded-full flex items-center justify-center
                          transition-colors duration-200
                          ${!day.isCurrentMonth ? 'text-gray-300' : ''}
                          ${day.isToday ? 'bg-yellow-100 border-2 border-yellow-400' : ''}
                          ${day.isSelected ? 'bg-yellow-500 text-white font-semibold' : ''}
                          ${!day.isCurrentMonth || isPastDate ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:bg-yellow-100'}
                        `}
                        onClick={() => handleDateSelect(day.date)}
                        disabled={!day.isCurrentMonth || isPastDate}
                      >
                        {day.date.getDate()}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* 时间段选择 */}
              {selectedDate && (
                <div className="fade-in">
                  <h3 className="text-lg font-medium text-gray-700 mb-4">
                    选择时间段（{selectedDate.toLocaleDateString('zh-CN')}）
                  </h3>
                  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                    {timeSlots.map((slot) => {
                      const isReserved = isSlotReserved(slot.id);
                      const isSelected = selectedTimeSlot === slot.id;
                      
                      return (
                        <button
                          key={slot.id}
                          className={`
                            py-2 px-3 rounded-lg text-sm
                            transition-colors duration-200
                            ${isReserved ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}
                            ${isSelected ? 'bg-yellow-500 text-white font-medium' : 'bg-white border border-gray-200 hover:bg-yellow-50'}
                          `}
                          onClick={() => handleTimeSlotSelect(slot.id)}
                          disabled={isReserved}
                        >
                          {slot.start} - {slot.end}
                        </button>
                      );
                    })}
                  </div>
                  {errors.time && (
                    <p className="mt-2 text-red-500 text-sm">{errors.time}</p>
                  )}
                </div>
              )}
            </div>

            {/* 用户信息表单 */}
            <div className="bg-white rounded-lg shadow-md p-6 fade-in">
              <h2 className="text-xl font-semibold text-gray-800 mb-6">
                填写个人信息
              </h2>
              <form onSubmit={handleSubmit} className="space-y-4">
                {/* 姓名输入 */}
                <div>
                  <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                    姓名 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    className={`
                      w-full px-4 py-2 border rounded-lg focus:ring-2 focus:outline-none
                      ${errors.name ? 'border-red-500 focus:ring-red-200' : 'border-gray-300 focus:ring-yellow-500 focus:border-yellow-500'}
                    `}
                    placeholder="请输入您的姓名"
                  />
                  {errors.name && (
                    <p className="mt-1 text-red-500 text-sm">{errors.name}</p>
                  )}
                </div>

                {/* 手机号码输入 */}
                <div>
                  <label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-1">
                    手机号码 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="tel"
                    id="phone"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    className={`
                      w-full px-4 py-2 border rounded-lg focus:ring-2 focus:outline-none
                      ${errors.phone ? 'border-red-500 focus:ring-red-200' : 'border-gray-300 focus:ring-yellow-500 focus:border-yellow-500'}
                    `}
                    placeholder="请输入您的手机号码"
                  />
                  {errors.phone && (
                    <p className="mt-1 text-red-500 text-sm">{errors.phone}</p>
                  )}
                </div>

                {/* 其他联系方式 */}
                <div>
                  <label htmlFor="otherContact" className="block text-sm font-medium text-gray-700 mb-1">
                    其他联系方式（选填）
                  </label>
                  <input
                    type="text"
                    id="otherContact"
                    name="otherContact"
                    value={formData.otherContact}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:border-yellow-500 focus:ring-yellow-500 focus:outline-none"
                    placeholder="微信或邮箱"
                  />
                </div>

                {/* 备注信息 */}
                <div>
                  <label htmlFor="remark" className="block text-sm font-medium text-gray-700 mb-1">
                    咨询内容备注（选填）
                  </label>
                  <textarea
                    id="remark"
                    name="remark"
                    value={formData.remark}
                    onChange={handleInputChange}
                    rows={3}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:border-yellow-500 focus:ring-yellow-500 focus:outline-none"
                    placeholder="请简要描述您的咨询需求"
                  />
                </div>

                {/* 提交按钮 */}
                <button
                  type="submit"
                  className="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-medium py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? (
                    <>处理中...</>
                  ) : (
                    <>提交预约</>
                  )}
                </button>
              </form>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
